package com.campus.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.campus.backend.bean.merchant.MerchantAuditBean;
import com.campus.backend.entity.Merchant;
import com.campus.backend.entity.MerchantApply;
import com.campus.backend.service.MerchantApplyService;
import com.campus.common.bean.common.PageQueryParam;
import com.campus.common.bean.common.Pagination;
import com.campus.common.bean.common.Resp;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 商户入驻申请表 前端控制器
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-05-21
 */
@Api(tags = "商户入驻申请接口")
@RestController
@RequestMapping("/merchant/apply")
public class MerchantApplyController {

    @Autowired
    private MerchantApplyService merchantApplyService;

    /**
     * 分页查询商户入驻申请列表
     * @param queryParam 查询参数
     * @return 分页结果
     */
    @ApiOperation("分页查询商户入驻申请列表")
    @GetMapping("/list")
    public Resp<Pagination<MerchantApply>> getMerchantApplyList(PageQueryParam queryParam, String name, String phone, Integer status) {
        PageInfo<MerchantApply> pageInfo = PageHelper.startPage(queryParam.getPageNo(), queryParam.getPageSize())
                .doSelectPageInfo(() -> {
                    LambdaQueryWrapper<MerchantApply> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.like(StringUtils.isNotBlank(name), MerchantApply::getName, name)
                            .like(StringUtils.isNotBlank(phone), MerchantApply::getPhone, phone)
                            .eq(status != null, MerchantApply::getStatus, status)
                            .orderByDesc(MerchantApply::getCreateTime);
                    merchantApplyService.list(queryWrapper);
                });
        return Resp.successPageable(pageInfo);
    }

    /**
     * 审核商户入驻申请
     * @param auditBean
     * @return 操作结果
     */
    @ApiOperation("审核商户入驻申请")
    @PostMapping("/audit")
    public Resp<Void> auditMerchantApply(@RequestBody @Valid MerchantAuditBean auditBean) {
        // 参数校验
        if (auditBean.getStatus() != 1 && auditBean.getStatus() != 2) {
            return Resp.error("审核状态参数错误");
        }
        if (auditBean.getStatus() == 2 && StringUtils.isBlank(auditBean.getRejectReason())) {
            return Resp.error("拒绝原因不能为空");
        }
        
        // 查询申请记录
        MerchantApply merchantApply = merchantApplyService.getById(auditBean.getId());
        if (merchantApply == null) {
            return Resp.error("申请记录不存在");
        }
        
        // 检查状态是否为待审核
        if (merchantApply.getStatus() != 0) {
            return Resp.error("该申请已审核，不能重复审核");
        }

        // 更新申请状态
        merchantApply.setStatus(auditBean.getStatus());
        merchantApply.setRejectReason(auditBean.getRejectReason());
        merchantApply.setUpdateTime(LocalDateTime.now());

        // 如果审核通过，则创建商户记录
        if (auditBean.getStatus() == 1) {
            Merchant merchant = new Merchant();
            // 复制基本信息
            BeanUtils.copyProperties(merchantApply, merchant);
            merchant.setId(null);
            // 设置默认值
            merchant.setRating(BigDecimal.valueOf(5.0)); // 默认评分5.0
            merchant.setSales(0); // 默认月销量0
            merchant.setStatus(0); // 默认休息中
            merchant.setCloseMethod(0); // 默认系统自动关闭
            merchant.setSupportDelivery(1); // 默认支持外卖
            merchant.setSupportDineIn(1); // 默认支持堂食
            merchant.setSupportTakeout(1); // 默认支持自取
            merchant.setInfoCompleted(0); // 默认信息未完善
            merchant.setCreateTime(LocalDateTime.now());
            merchant.setUpdateTime(LocalDateTime.now());
            merchantApplyService.auditMerchantApplyTransaction(merchantApply, merchant);
        } else {
            merchantApplyService.updateById(merchantApply);
        }
        
        return Resp.success();
    }
}
